import 'package:flutter/material.dart';
import '/utils/load_image.dart';
import '/utils/setting.dart';
import '/components/image_preview.dart';

// 聊天记录，每条记录的组件（头像 + 消息）
class ChatMsgItem extends StatelessWidget {
  final String userId; // 用户Id，默认设置自己为 '1'，对方为0，暂不考虑群聊
  final String content; // 消息内容
  final String avatarUrl; // 头像地址
  final String? contentType; // 消息类型，默认为文本

  const ChatMsgItem({
    super.key,
    required this.userId,
    required this.content,
    required this.avatarUrl,
    this.contentType,
  });

  @override
  Widget build(BuildContext context) {

    // 头像大小
    double avatarSize = 36.0;

    // 头像组件
    Widget avatarWidget = GestureDetector(
      onTap: () {
        // 点击头像，跳转到用户信息页面
        Navigator.pushNamed(context, 'UserInfoPage');
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(6.0),
        child: loadImageByUrl(avatarUrl, avatarSize, avatarSize),
      ),
    );

    // 文本聊天框
    Widget textWidget = ConstrainedBox(
      constraints: const BoxConstraints(
        maxWidth: 280,
      ),
      child: Stack(
        alignment: userId == '1' ? Alignment.centerRight : Alignment.centerLeft,
        clipBehavior: Clip.none, // 不裁剪子组件，即：超出不隐藏
        children: [
          Container(
            decoration: BoxDecoration(
              color: userId == '1' ? DefaultColor.wordBg : Colors.white,
              borderRadius: BorderRadius.circular(4.0),
            ),
            padding: const EdgeInsets.symmetric(vertical: 6.0, horizontal: 12.0),
            child: SelectableText(
              content,
              style: const TextStyle(
                  fontSize: 16.0,
                  color: Colors.black
              ),
            ),
          ),
          Positioned(
            top: 10,
            right: userId == '1' ? -6 : null,
            left: userId == '0' ? -6 : null,
            child: CustomPaint(
              size: const Size(6, 10), // 箭头的大小
              painter: ArrowPainter(
                color: userId == '1' ? DefaultColor.wordBg : Colors.white,
                direction: userId == '1' ? ArrowDirection.left : ArrowDirection.right,
              ),
            ),
          )
        ],
      ),
    );

    // 图片聊天框
    Widget imageWidget = Container(
      width: 100,
      height: 100,
      decoration: BoxDecoration(
        color: DefaultColor.wordBg,
        borderRadius: BorderRadius.circular(4.0),
      ),
      child: ImagePreview(imageUrl: content),
    );

    return Padding(
      padding: const EdgeInsets.only(top: 10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        textDirection: userId == '1' ? TextDirection.rtl : TextDirection.ltr,
        children: [
          avatarWidget, // 头像
          const SizedBox(width: 8.0),
          Visibility(
            visible: contentType == 'text',
            child: textWidget,
          ),
          Visibility(
            visible: contentType == 'image',
            child: imageWidget,
          ),
        ],
      ),
    );
  }
}

// 画箭头
enum ArrowDirection { left, right }

class ArrowPainter extends CustomPainter {
  final Color color;
  final ArrowDirection direction;

  ArrowPainter({required this.color, required this.direction});

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..style = PaintingStyle.fill;

    final path = Path();
    if (direction == ArrowDirection.right) {
      path.moveTo(size.width, 0);
      path.lineTo(size.width, size.height);
      path.lineTo(0, size.height / 2);
    } else {
      path.moveTo(0, 0);
      path.lineTo(0, size.height);
      path.lineTo(size.width, size.height / 2);
    }
    path.close();

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}